<template>
 <div class="detailContainer">
    <HeaderBar title="商品详情" :isBack="true"/>
    <LoginPop ref="loginPop" @onLoginSuccess="onOnLoginSuccess"/>
    <a-carousel v-if="productPictures.length>0" autoplay>
      <div v-for="item in productPictures" :key="item.picId" >
        <img :src="item.BigUrl" alt="" style="width:100%;height:400px"/>
      </div> 
    </a-carousel>
    <div class="detail-content" v-if="goodsInfo!=null">
        <div class="prices">
            <div class="priceDesc" v-if="logined" style="display: flex;">{{goodsInfo.Price}}<div class="huaxian">{{goodsInfo.OldPrice}}</div></div>
            <div  v-else>{{goodsInfo.OldPrice}}</div>
            <div class="importPrie" v-if="admin">成本价：{{ goodsInfo.ProductCost }}</div>
        </div>
        <div class="productName">{{goodsInfo.Name}}</div>
        <div class="saleStatus">
            <div class="statusItem"><img src="../assets/images/salesIcon.png" alt="">已售：{{goodsInfo.SaleVolume}}</div>
            <div class="statusItem"><img src="../assets/images/kucun.png" alt="" class="kucunIcon">库存：{{goodsInfo.StockQuantity}}</div>
            <!-- <div class="statusItem"><img src="../assets/images/huoj.png" alt="">杭州发货</div> -->
        </div>
        <div class="line"></div>
        <div class="attrList" @click="showAttr">
            <div>选择 · 规格</div>
            <a-icon type="right" style="color: #999;margin-right: 10px;"/>
        </div>
        <div class="line"></div>
        <div class="desc" >
            <div class="descTitle">· 宝贝详情 ·</div>
            <div v-html="goodsInfo.Full"></div>
        </div>
    </div>
    <div class="footerInfo">
        <!-- <div class="footerItem">
            <img src="../assets/images/yinyu-kefu.png" alt="客服">
            <div>客服</div>
        </div> -->
        <div class="footerItem" @click.prevent="gotoHome">
            <img src="../assets/images/dianpu.png" alt="首页">
            <div>首页</div>
        </div>
        <div class="footerItem" @click.prevent="gotoCart">
            <!-- <div class="cartNum">{{ cartNum }}</div> -->
            <img src="../assets/images/daohanggouwuche.png" alt="购物车">
            <div>购物车</div>
        </div>
        <div class="addToCart" @click.prevent="addCart">加入购物车</div>
        <div class="order" @click.prevent="createOrder">立即下单</div>
    </div>
    <div class="modal" v-if="showAttrList" @click="hideAttrList">
        <div class="attrModal" @click.stop="">
            <div class="attrLists">
                <div 
                    :class="['attrItem', selectedAttr && selectedAttr.value === item.value ? 'selected' : '']" 
                    v-for="(item) in attrLists" 
                    :key="item.value" 
                    @click.stop="selectAttr(item)">
                    {{ item.name }}
                </div>
            </div>
            <div style="background-color: #e0e0e0;height: 2px;width: 100%;"></div>
            <div class="remainInfo" >
                数量 <span v-if="selectedAttr">{{ "（库存剩余"+selectedAttr.qty+"）" }}</span>
            </div>
            <div class="selectInfo" >
                <div style="flex: 1;"></div>
                <div class="sizeOption">
                    <el-input-number v-model="selectedNumber" @change="handleChange" :min="minSize" :max="maxSize" label="描述文字"></el-input-number>
                </div>
            </div>

            <div style="background-color: #e0e0e0;height: 2px;width: 100%;margin-top: 20px;"></div>
            <div class="finalPrice">
                <div style="flex: 1;text-align: left;">价格：</div>
                <div class="priceInfo">
                    ￥{{ selectedPrice }}
                </div>
            </div>
        </div>

    </div>
 </div>
</template>
<script>
    import {getGoodsInfo,getGoodAttrs,goodsToCart,goodsCheckout} from "../api/product.js";
    import { getPaymentMethod,getUserRoles } from "@/api/user.js";
    import HeaderBar from "../components/Header.vue";
    import LoginPop from '@/components/popup/LoginPop.vue';
    export default {
        name: "DetailView",
        data(){
            return{
                goodsInfo:null,
                attrLists:[],
                productPictures:[],
                showAttrList:false,
                cartNum:0,
                selectedNumber:1,
                selectedAttr:null,
                prodId:"",
                minSize:1,
                maxSize:100,
                defaultPayment:'',
            }
            
        },
        computed:{
            selectedPrice(){
                //console.log("计算价格",this.selectedAttr,this.goodsInfo);
                if(this.selectedAttr!=null){
                    //console.log('1')
                    return Number(this.selectedAttr.price)*10 * this.selectedNumber /10;}
                else{
                    //console.log('2',)
                    return Number(this.goodsInfo.Price.toString().substring(1))*10 * this.selectedNumber /10;
                }
                   
            },
            logined(){
                return localStorage.getItem('userToken')&&localStorage.getItem('userInfo');
            },
            admin(){
                return this.isAdmin==1;
            }
        },
        
        components:{
            HeaderBar,
            LoginPop
        },
        mounted(){
            // //console.log(this.$route.query);
            this.prodId=this.$route.query.id;
            this.getGoodsDetail(this.$route.query.id);
            if(localStorage.getItem('userToken')){
                getPaymentMethod().then((res)=>{
                //console.log(res);
                    if(res.Code==200&&res.Data.length>0){
                        this.defaultPayment=res.Data[0].PaymentMethodSystemName;
                    }
                });
                getUserRoles().then((res)=>{
                    if(res.Code==200&&res.Data.length>0){
                        console.log(res);
                        for(let i = 0;i<res.Data.length;i++){
                            if(res.Data[i].SystemName == 'Operators'||res.Data[i].SystemName == 'Agents'){
                                this.isAdmin=1;
                                break;
                            }
                        }
}
                        // this.isAdmin=res.Data[0].IsAdmin;
                    });
            }
            
        },
        methods:{
            onOnLoginSuccess(){
                getPaymentMethod().then((res)=>{
                //console.log(res);
                    if(res.Code==200&&res.Data.length>0){
                        this.defaultPayment=res.Data[0].PaymentMethodSystemName;
                    }
                 });
            },
            addCart(){
                //console.log("加入购物车",this.selectedNumber,this.selectedAttr);
                if(!this.showAttrList){
                    this.showAttr();
                }else{
                    let query = {
                        PId: this.prodId,
                        Qty: this.selectedNumber,
                        AttrValue: this.selectedAttr?JSON.stringify([this.selectedAttr.value]):''
                    }
                    goodsToCart(query).then((res)=>{
                        if(res.Code==200){
                            this.$message.success('加入购物车成功')
                        }else{
                            this.$message.error('加入购物车失败')
                            if(res.Code==401){
                                console.log("需要登录");
                                this.$refs.loginPop.open();
                            }
                        }
                         this.showAttrList=false;
                         
                    });
                }
            },
            createOrder(){
                //console.log("立即下单",this.goodsInfo);
                if(!this.showAttrList){
                    this.showAttr();
                }else{
                    let query={
                        PaymentMethod: this.defaultPayment,
                        Balance: 0,
                        AddressId: 0,
                        // "Address": {
                        //     "Id": 0,
                        //     "Name": "string",
                        //     "Phone": "string",
                        //     "ProvinceName": "string",
                        //     "CityName": "string",
                        //     "AreaName": "string",
                        //     "Address": "string",
                        //     "Default": true,
                        //     "Fields": [
                        //     {
                        //         "Id": 0,
                        //         "Name": "2214",
                        //         "DefaultValue": "string"
                        //     }
                        //     ]
                        // },
                        OrderTotal:this.selectedPrice,
                        Remark: "",
                        GoodsValues: [
                            {
                                Sku: this.selectedAttr?this.selectedAttr.Sku:this.goodsInfo.Sku,
                                Qty: this.selectedNumber
                            }
                        ]
                        }
                    goodsCheckout(query).then((res)=>{
                        if(res.Code==200){
                            this.$message.success('下单成功')
                        }else{
                            this.$message.error('下单失败')
                            if(res.Code==401){
                                console.log("需要登录");
                                this.$refs.loginPop.open();
                            }
                        }
                         this.showAttrList=false;
                         
                         
                    });
                }
            },


            handleChange(){
                //console.log(this.selectedNumber);
            },
            selectAttr(item){
                if(this.selectedAttr!=null && this.selectedAttr.value==item.value){
                    this.selectedAttr=null;
                }else{
                    this.selectedAttr=item;
                    this.maxSize=this.selectedAttr.qty;
                }

               
                this.selectedNumber=1;
                
                //console.log(this.selectedAttr);
            },
            gotoCart(){
                this.$router.push("/cart");
            },
            gotoHome(){
                this.$router.push("/");
            },
            getGoodsDetail(param){
                let query={
                    id:param
                };
                getGoodsInfo(query).then((res)=>{
                    this.goodsInfo=res.Data;
                    this.goodsInfo.OldPrice = res.Data.OldPrice?res.Data.OldPrice:'￥0.00';
                    // this.goodsInfo.Full = this.goodsInfo.Full.replace(/https:\/\/demo.urshop.cn/g,"http://123.56.164.38:8081");

                    for(let idx = 0;idx<this.goodsInfo.Pictures.length;idx++){
                        this.productPictures.push({
                            BigUrl:this.goodsInfo.Pictures[idx].BigUrl,
                            picId:idx
                        });
                    }
                    // //console.log(this.goodsInfo);
                }).catch((err)=>{
                    console.log(err);
                })
            },
            showAttr(){
                this.attrLists=[];
                getGoodAttrs({pid:this.prodId}).then((res)=>{
                    let attr = res.Data.attrs[0];
                    //console.log(attr);
                    for(let index = 0;index< attr.attrValArr.length;index++){
                        //此处有一个坑，数据结构对不上，需要转换一下
                        let tmpItem = attr.attrValArr[index];
                        //console.log(tmpItem);
                        this.attrLists.push({
                            value:tmpItem.value,
                            name:tmpItem.name,
                            price:res.Data.tables[index].info.price,
                            qty:res.Data.tables[index].info.qty,
                            sku:res.Data.tables[index].info.sku
                        });
                    }
                    //console.log(this.attrLists);
                    this.showAttrList=!this.showAttrList;
                }).catch((err)=>{
                    console.log(err);
                    this.showAttrList=!this.showAttrList;
                })

                
            },
            hideAttrList(){
                this.showAttrList=false;
            }
        }
    }
</script>
<style scoped>
.detailContainer{
    background-color: #950000;
    height: 100%;
    width: 100vw;
    display: flex;
    flex-direction: column;
    overflow: auto;
}
.huaxian{
    font-size: smaller;
    color: gray;
    text-decoration: line-through;
    margin-left: 15px;
    margin-top: 2px;
}
.detail-content{
    height: 89% ;
    background-color: #fff;
    text-align: left;
    padding-bottom: 50px;
}
.prices{
    padding:0 10px;
    color: #950000;
    font-size: 20px;
    line-height: 40px;
    font-weight: 600;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.productName{
    padding:0 10px;
    font-size: 16px;
    line-height: 30px;
    font-weight: 600;
}
.saleStatus{
    padding:10px 30px;
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    color: #999;
}
.statusItem{
    display: flex;
    align-items: center;
}
.statusItem img{
    width: 16px;
    height: 16px;
    object-fit: contain;
    margin-right: 5px;
}
.kucunIcon{
    width: 14px !important;
    height: 14px !important;
}
.attrList{
    padding: 10px;
    font-size: 14px;
    display: flex;
    justify-content: space-between;
    align-items: center;

}
.line{
    margin-top: 5px;
    height: 3px;
    background-color: #ddd;
    width: 100%;
}
.modal {
  position: fixed; /* 保持在屏幕上 */
  z-index: 1; /* 位于顶层 */
  left: 0;
  top: 0;
  width: 100%; /* 全屏宽 */
  height: 92%; /* 全屏高 */
  overflow: auto; /* 启用滚动条 */
  background-color: rgb(0,0,0); /* 背景色 */
  background-color: rgba(0,0,0,0.4); /* 背景透明度 */
}
.attrModal{
    min-height: 200px;
    background-color: white;
    width: 100%;
    bottom: 0;
    position: absolute;
}
.attrLists{
    display: flex;
    align-items: center;
    flex-wrap: wrap;

}
.attrItem{
    padding: 5px 10px;
    margin: 10px;
    background-color: #fff;
    color: #333;
    border: #ddd solid 1px;
    border-radius: 3px;
    font-size: 16px;
}
.selected{
    background-color: red;
    color: white;
    border: red solid 1px;
}
.descTitle{
    text-align: center;
    font-size: 20px;
    font-weight: 600;
    line-height: 40px;
}
.footerInfo{
    position: fixed;
    bottom: 3px;
    width: 100vw;
    background-color: #fff;
    height: 50px;
    display: flex;
}
.footerInfo{
    padding: 0 10px;
}
.addToCart{
    line-height: 50px;
    flex:1;
    background-color: orange;
    margin-left: 10px;
    font-size: 16px;
    color: white;

}
.order{
    line-height: 50px;
    flex:1;
    background-color: red;
    font-size: 16px;
    color: white;
}
.footerItem{
    width: 40px;
    height: 50px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    font-size: 12px;
    position: relative;
}
.cartNum{
    position: absolute;
    top: -5px;
    right: -2px;
    color: white;
    font-size: 10px;
    width: 16px;
    height: 16px;
    border-radius: 8px;
    background-color: red;
    line-height: 16px;
}
.footerItem img{
    width: 20px;
    height: 20px;
    object-fit: cover;
}
.remainInfo{
    padding-left: 10px;
    text-align: left;
    font-size: 16px;
    line-height: 30px;
}
.selectInfo{
    display: flex;
    align-items: center;
}
.finalPrice{
    display: flex;
    justify-content: space-between;
    padding: 0 10px;
    font-size: 16px;
    font-weight: 400;
}
.priceInfo{
    font-weight: 600;
    color: #950000;
}
.remainInfo span{
    color: #ccc;
    font-size: 14px;
    line-height: 30px;
}
::v-deep p img{
    width: 100%;
    height: auto;
}
</style>